const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const fs = require("fs");

const main = require("./crawl");

const heros = [];

class Hero {
  constructor(
    codeName,
    gender,
    combatExperience,
    origin,
    birth,
    race,
    height,
    condition
  ) {
    this.codeName = codeName;
    this.gender = gender;
    this.combatExperience = combatExperience;
    this.origin = origin;
    this.birth = birth;
    this.race = race;
    this.height = height;
    this.condition = condition;
  }
}

function getHeros() {
  const fileName = "../data/干员一览.html";
  const heros = [];

  return new Promise((resolve, reject) => {
    fs.readFile(fileName, (err, data) => {
      if (err) {
        reject(err);
      }

      const { document } = new JSDOM(data).window;
      const allHeros = document.querySelectorAll(".smwdata");
      allHeros.forEach((ele) => {
        heros.push(ele.attributes.getNamedItem("data-cn").value);
      });
      resolve(heros);
    });
  });
}

function process_hero(hero) {
  const fileName = main.dataDir + "/" + hero + ".html";
  fs.readFile(fileName, (err, data) => {
    if (err) {
      console.log(err);
    } else {
      const { document } = new JSDOM(data).window;
      const infoList = [];

      const headEle = document.querySelector("#干员档案");
      const heroDetail =
        headEle.parentElement.nextElementSibling.nextElementSibling;
      const allTextInfo = heroDetail.querySelectorAll("p");
      allTextInfo.forEach((p) => {
        infoList.push(p.textContent.trim().replaceAll("\n", ""));
      });

      const personalInfo = [];
      let re = /】([^【]+)【?/gm;
      //   console.log(infoList);
      let found = infoList[infoList.indexOf("基础档案") + 1].matchAll(re);
      for (const prop of found) {
        personalInfo.push(prop[1]);
      }
      heros.push(
        new Hero(
          personalInfo[0],
          personalInfo[1],
          personalInfo[2],
          personalInfo[3],
          personalInfo[4],
          personalInfo[5],
          personalInfo[6],
          personalInfo[7]
        )
      );
      console.log(heros);
    }
  });
}

exports.heros = getHeros;
exports.process_hero = process_hero;

process_hero("陈");
